package service

import (
	"errors"
	"fmt"
	"go_web/dao"
	"go_web/models"
	"go_web/utils"
)

func Login(userName, passwd string) (*models.LoginRes, error) {

	passwd = utils.Md5Crypt(passwd, "xdd")

	fmt.Println(passwd)

	user := dao.GetUser(userName, passwd)

	if user == nil {
		//登录失败
		return nil, errors.New("账号密码不正确")

	}

	uid := user.Uid
	//利用uid 生成token jwt 令牌

	token, err := utils.Award(&uid)
	if err != nil {
		//登录失败
		return nil, errors.New("Token 获取失败")

	}

	userInfo := models.UserInfo{
		Uid:      uid,
		UserName: user.UserName,
		Avatar:   user.Avatar,
	}

	var loginRes = &models.LoginRes{
		Token:    token,
		UserInfo: userInfo,
	}

	return loginRes, nil

}
